<?php

class TwicturesSearchWidget {

    private $directory = ''; // Directory in which script resides
    private $templates = array(); // A list of templates found
    private $cache_path = './cache'; // Cache directory
    private $templates_feed = 'http://zetaprints.com/?page=api-search;Search=twictures;GeneratePrintPdf=image;SortBy=1;Qty=50'; //Zetaprints search api url
    private $twictures_url = "http://ec2-174-129-95-130.compute-1.amazonaws.com/tw/tw.php"; // Twictures script url
    private $cache_duration = 3600; // Templates feed cache duration in seconds
    private $root_path = '../'; //Path to root directory of the site
    private $root_url = ''; // URL of site
    private $errors = array();

    //Constructor
    public function TwicturesSearchWidget($root_path="../"){
        require_once (dirname(__FILE__) . '/simplepie.inc.php');
        $this->root_path=$root_path;
        $this->setPaths();
        if(!file_exists($this->cache_path)){
            if(!mkdir($this->cache_path)){
                throw new Exception('Failed to create cache directory check permissions or create it manually');
            }
        }
        elseif(!is_writable($this->cache_path)){
            throw new Exception('Cache directory is not writable');
        }
        if(!file_exists($this->cache_path.'/images')){
            mkdir($this->cache_path.'/images');
        }
    }
    
    //Sets paths to files and directories
    private function setPaths(){
        $this->directory = dirname(__FILE__);
        $this->cache_path = $this->directory. '/' .$this->cache_path; 
        if(substr($this->root_path,0,1) == '.'){
            $this->root_path=$this->directory . '/' . $this->root_path;
        }
        $root_path = realpath($this->root_path);
        $root_path = str_replace('\\','/',$root_path);
        $this->root_path = $root_path;
        $this->root_url = isset($_SERVER['HTTPS']) ? "https://" : "http://" . $_SERVER['HTTP_HOST'];
    }

    //Sets given list of templates to property
    private function setTemplates($templates){
        $result = array();
        foreach($templates as $template){
            $id=$template->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'id');
            $id=$id[0]['data'];
            $thumbnail = $template->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'thumbnail');
            $thumbnail = $thumbnail[0]['data'];
            $thumbnail_file=basename($thumbnail);
            $thumbnail_file=str_replace('\\','_',$thumbnail_file);
            if(!file_exists($this->cache_path . '/images/' . $thumbnail_file)){
                file_put_contents($this->cache_path . '/images/' . $thumbnail_file, file_get_contents($thumbnail));
            }
            $thumbnail = realpath($this->cache_path . '/images/' . $thumbnail_file);
            $thumbnail = str_replace('\\', '/', $thumbnail);
            $thumbnail = $this->root_url . str_replace($this->root_path, '', $thumbnail);
            $result[]=array('title'=>$template->get_title(), 'id' => $id, 'link' => $template->get_link(), 'thumbnail' => $thumbnail);
        }
        $this->templates = $result;
    }

    //Get list of templates
    private function getTemplates() {
        set_time_limit(0);
        $feed = new SimplePie($this->templates_feed, $this->cache_path);
        $feed->set_cache_duration($this->cache_duration);
        $success = $feed->init();
        if(!$success){
            throw new Exception('Failed to load templates feed');
        }
        else{
            $feed->handle_content_type();
            $feed_items = $feed->get_items();
            if(count($feed_items)){
                $this->setTemplates($feed_items);
            }
            else{
                throw new Exception('Template feed is empty');
            }
        }
    }
    //Displays widget
    public function showWidget($form_action) {
        $this->getTemplates();
        $errors = $this->errors;
        $templates = $this->templates;
        require('views/widget.php');
    }
    //Gets a short URL and shows results view. Shows widget view with errors if failed
    public function showResults($data) {
        if(!isset($data['template_id']) or !strlen($data['template_id'])){
            $this->errors[] = 'Template ID is required';
        }
        if (!isset($data['twitter']) or !strlen($data['twitter'])) {
            $this->errors[] = 'Twitter username is required';
        }
        if (!count($this->errors)){
            $url = $this->twictures_url . "?template_id=$data[template_id]&rss_feed=http://twitter.com/statuses/user_timeline/$data[twitter].rss&get_shorttag=1";
            if(isset($data['size_x']) and intval($data['size_x']) and isset($data['size_y']) and intval($data['size_y'])){
                $url .= "&size=" . intval($data['size_x']) . "x" . intval($data['size_y']);
            }
            $short_url = file_get_contents($url);
            if(substr($short_url,0,4) != "http"){
                $this->errors[] = $short_url;
            }
        }
        if (!count($this->errors)) {
            $twitter=$data['twitter'];
            require('views/result.php');
        } else {
            foreach ($this->errors as $err) {
                echo "error: $err \n";
            }
        }
    }
}
